package com.jingdianjichi.subject.domain.util;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 缓存工具类
 */
@Component
public class CacheUtil<T> {
    private Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.HOURS)
            .build();

    //    Function<String,List<T>> String是入参，List<T>是出参
    public List<T> getResult(String key, Class<T> clazz, Supplier<List<T>> function) {
        List<T> result = new LinkedList<>();
        String content = localCache.getIfPresent(key);
        if (!StringUtils.isEmpty(content)) {
            result = JSON.parseArray(content, clazz);
        } else {
            result = function.get();
            if (!CollectionUtils.isEmpty(result)) {
                localCache.put(key, JSON.toJSONString(result));
            }
        }
        return result;
    }
}
